package com.zzyl.intercept;

import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenConfigProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserJwtTokenInterceptor implements HandlerInterceptor {

    private final JwtTokenConfigProperties jwtTokenConfigProperties;

    public UserJwtTokenInterceptor(JwtTokenConfigProperties jwtTokenConfigProperties) {
        this.jwtTokenConfigProperties = jwtTokenConfigProperties;
    }

    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    //获取请求头的key 获得token 放到threadlocal
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (ObjectUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        Claims claims = JwtUtil.parseJWT(jwtTokenConfigProperties.getBase64EncodedSecretKey(),token);
        if (ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        Long userId = Long.valueOf((Integer) claims.get("userId")) ;
        //放到本地线程Threadlocal
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove(); //请求线程结束，销毁  -----
    }
}
















